package com.liangzong.betspider.task;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.WebDriver;

import java.util.UUID;

import static com.liangzong.betspider.utils.DriverUtil.getChromeDriver;
import static com.liangzong.betspider.utils.DriverUtil.getChromeDriverRemote;
import static com.liangzong.betspider.utils.SpiderInfoUtil.register2RefreshList;

@Slf4j
@Data
public class Process extends Thread {
    private final StartSpiderTask startSpiderTask;
    boolean reverse;
    int port;
    long pauseTime;
    int overTime;
    String sessionId;
    private volatile boolean stop;
    WebDriver driver;
    CycleTask cycleTask;
    WatchDataTask watchDataTask;

    public Process(StartSpiderTask startSpiderTask, boolean reverse, int port, long pauseTime, int overTime) {
        this.startSpiderTask = startSpiderTask;
        this.reverse = reverse;
        this.port = port;
        this.pauseTime = pauseTime;
        this.overTime = overTime;
    }

    public boolean stopWork() throws InterruptedException {
        cycleTask.stopCycleTask();
        watchDataTask.stopWatchDataTask();
        while (true) {
            if (cycleTask.isStoped() && watchDataTask.isStoped() && this.driver != null) {
                try {
                    driver.close();
                } catch (Exception e) {
                    log.error("关闭浏览器异常");
                }
                break;
            }
            Thread.sleep(1000);
        }
        log.info("停止工作");
        return true;
    }

    @Override
    public void run() {
        sessionId = UUID.randomUUID().toString();
        //注册到刷新列表
        register2RefreshList(sessionId);
        driver = getChromeDriverRemote(startSpiderTask.chromeDriverConfig, port);

        //点击各个球赛的链接
        cycleTask = new CycleTask(sessionId, driver, pauseTime, reverse,startSpiderTask.chromeDriverConfig, port);
        cycleTask.setDaemon(true);
        cycleTask.start();

        //监听数据
        watchDataTask = new WatchDataTask(sessionId, driver, overTime, port);
        watchDataTask.setDaemon(true);
        watchDataTask.start();
    }
}
